package com.spogher.bsc.pages;

import java.util.List;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;

import com.spogher.bsc.data.dao.interfaces.ManagerDao;
import com.spogher.bsc.data.dataobjects.Manager;

public class ManagerPage extends BscTemplatePage{
	
	@SpringBean
	ManagerDao managerDao;

	public ManagerPage() {
		super();
		Form<Manager> managerForm = new Form<Manager>("managerForm", new CompoundPropertyModel<Manager>(new Manager()));
		managerForm.add(new TextField<String>("name").setRequired(true));
		managerForm.add(new TextField<String>("surname").setRequired(true));
		managerForm.add(new TextField<String>("email").setRequired(true));
		managerForm.add(new PasswordTextField("password").setRequired(true));
		
		final WebMarkupContainer wmc = new WebMarkupContainer("listContainer");
		
		wmc.add(new ListView<Manager>("list", new PropertyModel<List<Manager>>(this, "managerDao.findAll")){

			private static final long serialVersionUID = 1L;

			@Override
			protected void populateItem(ListItem<Manager> item) {
				Manager manager = item.getModelObject();
				item.add(new Label("managerName", manager.getName()));
				item.add(new Label("managerSurname", manager.getSurname()));
				item.add(new Label("managerEmail", manager.getEmail()));			
			}
			
		});
		wmc.setOutputMarkupId(true);
		add(wmc);
		
		managerForm.add(new AjaxSubmitLink("submit"){
			private static final long serialVersionUID = 1L;

			@Override
			protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
				Manager manager = (Manager) form.getModelObject();
				Manager newManager = new Manager();
				newManager.setName(manager.getName());
				newManager.setSurname(manager.getSurname());
				newManager.setEmail(manager.getEmail());
				newManager.setPassword(manager.getPassword());
				managerDao.save(newManager);
				target.addComponent(wmc);
			}
		});
		
		
		add(managerForm);
	}
}
